package com.hyg.module_third_party_demo.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Environment;
import android.util.Log;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.hyg.lib_common.constant.Constants;
import com.hyg.module_third_party_demo.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.http.Url;

@Route(path = Constants.PATH_ACTIVITY_MODULE_DEMO_OKHTTP)
public class OkHttp3Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ok_http3);
    }

    /**
     * @description 设置请求头部
     * @author visitant
     * @time 2020/11/17 10:38
     */
    public void setHttpHeader() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://github.com")
                .header("User-Agent", "My super agent")
                .addHeader("Accept", "text/html")
                .build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            if (!response.isSuccessful()) {
                throw new IOException("服务器端错误: " + response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @description get方式
     * @author visitant
     * @time 2020/11/17 10:37
     */
    public void httpGet(String url) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response response = null;
        try {
            response = client.newCall(request).execute();           //同步方式
            String result = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @description post json方式
     * @author visitant
     * @time 2020/11/17 10:39
     */
    public void httppost(String url, String json, Callback callback) {
        OkHttpClient client = new OkHttpClient();
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
//        try {
//            Response response = client.newCall(request).execute();//同步
//            String result=response.body().string();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        client.newCall(request).enqueue(callback);                  //异步
    }


    /**
     * @description 键值对提交
     * @author visitant
     * @time 2020/11/17 10:43
     */
    public void httpMap(String url, String json, Callback callback) {
        OkHttpClient client = new OkHttpClient();
        RequestBody Body = new FormBody.Builder()
                .add("platform", "android")
                .add("name", "bug")
                .add("subject", "XXXXXXXXXXXXXXX")
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(Body)
                .build();
        client.newCall(request).enqueue(callback);
    }


    /**
     * @description form 提交
     * @author visitant
     * @time 2020/11/17 10:41
     */
    public void httpForm(Callback callback) {
        OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("search", "Jurassic Park")
                .build();
        Request request = new Request.Builder()
                .url("https://en.wikipedia.org/w/index.php")
                .post(formBody)
                .build();
        client.newCall(request).enqueue(callback);
//      Call call= client.newCall(request);               //取消
//      call.enqueue(callback);
//      call.cancel();
    }

    /**
     * @description 文件上传
     * @author visitant
     * @time 2020/11/17 10:50
     */
    public void httpIoFile(Callback callback) {
        String IMGUR_CLIENT_ID = "...";
        MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("title", "Square Logo")
                .addFormDataPart("image", "logo-square.png",
                        RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
                .build();
        Request request = new Request.Builder()
                .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
                .url("https://api.imgur.com/3/image")
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(callback);
    }


    /**
     * @description 文件下载
     * @author visitant
     * @time 2020/11/17 10:53
     */
    public void downLoadFile(String fileUrl, String name) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(fileUrl).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    ResponseBody body = response.body();
                    if (body != null) {
                        writeFile(name, body);
                    }
                }
            }
        });
    }


    /**
     * @description 文件写入
     * @author visitant
     * @time 2020/11/17 10:57
     */
    private void writeFile(String fileName, ResponseBody body) {
        InputStream is = null;  //网络输入流
        FileOutputStream fos = null;  //文件输出流
        is = body.byteStream();
        String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + fileName;
        File file = new File(filePath);
        try {
            fos = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int len = 0;
            long totalSize = body.contentLength();  //文件总大小
            long sum = 0;
            while ((len = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                sum += len;
                int progress = (int) (sum * 1.0f / totalSize * 100);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}